---
--- 处理灰度标签具体函数
--- Created by E.T.
--- DateTime: 2018/10/25 11:35
---
local eureka = require "kong.plugins.gray.tools.eureka_apps"
local string_tools = require "kong.plugins.gray.tools.string_tools"
local http_tools = require "kong.plugins.gray.tools.http_tools"
local config = require "kong.plugins.gray.tools.config"

local request = kong.request
local service = kong.service
local log = kong.log
local _M = {}

local function is_empty(tbl)
    if next(tbl) ~= nil then
        return false
    else
        return true
    end
end

--跳转至上游服务
local function set_upstream(app_name)
    local ok, err = service.set_upstream(app_name)
    if not ok then
        kong.log.err("跳转至上游服务出错：",err)
        http_tools.response(403, app_name .. "没有找到上游服务")
    end
end

--处理灰度应用方法（需要自己实现负载，暂时不用）
local function gray_app(apps, app_name, path, query)
    for tk, tv in pairs(apps) do
        --log.notice("app->", tk, tv)
        if string.upper(tk) == string.upper(app_name) then
            if is_empty(tv.gray) then
                log.notice("没有灰度实例")
                http_tools.response(403, app_name .. "没有灰度实例")
            end
            log.notice("跳转至灰度实例->", tk)
            --跳转至灰度实例
            service.set_target("10.10.13.124", 8080)
            service.request.set_path(path)
            service.request.set_raw_query(query)
        end
    end
end

--跳转至kong 上游服务，由kong实现负载
local function jump_upstream(apps, app_name, tag)
    for tk, tv in pairs(apps) do
        if string.upper(tk) == string.upper(app_name) then
            if tag == config.gray_tag_value then
                if is_empty(tv.gray) then
                    log.notice("没有灰度实例")
                    http_tools.response(403, app_name .. "没有灰度实例")
                end
                log.notice("跳转至灰度实例->", app_name.."-gray")
                --跳转至灰度实例上游
                set_upstream(app_name.."-gray")
            else
                log.notice("跳转至正常实例->", app_name)
                --跳转至正常实例上游
              set_upstream(app_name)
            end
        end
    end
end

local function do_tag(conf)
    --local query = request.get_raw_query()
    local tag = request.get_header("tag-gray")
    local path = request.get_path()
    local app_name = string_tools.split(path, "/")
    --path = string_tools.remove_path_first(path, "/")
    log.notice("灰度标识-->", tag)
    log.notice("请求路径-->", path)
    --log.notice("请求参数-->", query)
    local apps = eureka.get_eureka_apps(conf)
    jump_upstream(apps, app_name[1], tag)
end

function _M.execute(conf)
    local ok, err = do_tag(conf)
end

return _M
